package cn.itcast.demo.web;

import cn.itcast.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;


@Slf4j
@RestController
@RequestMapping("user")
public class UserController {


    /**
     * 传统的Handler
     * 同步阻塞
     *
     * @return
     */
    @GetMapping("/sync")
    public ResponseEntity<User> getUserSync() {
        log.info("sync 开始执行");
        User user = getUser();
        log.info("sync 执行完毕");
        return ResponseEntity.ok(user);
    }

    // 生成user的方法
    private User getUser() {
        try {
            // 模拟业务耗时1秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.of("Rose", 18);
    }

    /**
     * 异步的Handler
     * 返回结果不是数据,而是弹射器
     *
     * @return
     */
    @GetMapping("/mono")
    public Mono<User> getUserMono() {
        log.info("mono 开始执行");
        // 封装数据的过程是异步
        Mono<User> mono = Mono.fromSupplier(this::getUser);
        log.info("mono 执行完毕");
        return mono;
    }


    // Flux是弹射器,没有常规的方法及API

    /**
     * 普通Flux模式
     *
     * @return
     */
    @GetMapping("/flux")
    public Flux<User> getUserFlux() {
        log.info("flux 开始执行");
        Flux<User> flux = getUserWithFlux();
        log.info("flux 执行完毕");
        return flux;
    }

    private Flux<User> getUserWithFlux() {
        return Flux.interval(Duration.ofSeconds(1))// 每隔1秒发射一个元素
                .take(100) // 取前3个元素
                // 将元素转为一个User对象,i的默认值为0
                .map(i -> User.of("user_" + i, 20 + i.intValue()));
    }

    /**
     * 返回文本事件流
     * 每封装完成一次就向外弹射一次
     *
     * @return
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserStream() {
        log.info("stream 开始执行");
        Flux<User> flux = getUserWithFlux();
        log.info("stream 执行完毕");
        return flux;
    }

    /**
     *  创建Flux的API
     */
    @GetMapping("/jdd")
    public void testJd() {
        Flux<Integer> flux = Flux.create(sink -> {
            for (int i = 0; i < 10; i++) {
                // 将循环遍历得到的数字，添加到flux
                sink.next(i);
            }
            // 循环结束，任务完成
            sink.complete();
        });
        // 会生成一个包含从0到9的int元素的Flux
        flux.subscribe(System.out::println);
    }
}